package edu.um.variable;

import java.util.ArrayList;
import java.util.List;

import edu.um.expression.ExpressionTreeNode;

public class VariableInArray extends Variable {

  private final ArrayVariable arrayVariable;

  private final List<ExpressionTreeNode> indexExpressions;

  public VariableInArray(String name, ArrayVariable theArrayVariable, List<ExpressionTreeNode> theIndexExpressions) {
    super(name, theArrayVariable.getSubType());
    this.arrayVariable = theArrayVariable;
    this.indexExpressions = theIndexExpressions;
  }

  @Override
  public Object getValue() {
    List<Integer> indexes = evaluateIndexExpressions();
    if (indexes == null) {
      return null;
    }
    return arrayVariable.getValueAt(indexes);
  }

  @Override
  public void setValue(Object value) {
    List<Integer> indexes = evaluateIndexExpressions();
    if (indexes != null) {
      arrayVariable.setValueAt(indexes, value);
    }
  }

  private List<Integer> evaluateIndexExpressions() {
    List<Integer> indexes = new ArrayList<Integer>();
    for (ExpressionTreeNode expressionNode : indexExpressions) {
      Object expressionValue = expressionNode.evaluate();
      if (expressionValue == null) {
        return null;
      }
      indexes.add((Integer) expressionValue);
    }
    return indexes;
  }
}
